package org.ruanjj.longestPalindrome;

public class Solution1 {
    //动态规划法
    public String longestPalindrome(String s){
        int length = s.length();
        int maxLen = 1;
        int begin = 0;
        if(length < 2){
            return s;
        }
        boolean[][] dp = new boolean[length][length];
        for(int i = 0; i < length; i++){
            dp[i][i] = true;
        }

        for(int L = 2; L <= length; L++){
            for(int i = 0; i < length; i++){
                int j = L-1+i;

                if(j >= length || j < i){
                    break;
                }

                if(s.charAt(i) != s.charAt(j)){
                    dp[i][j] = false;
                }else{
                    if(L <= 3){
                        dp[i][j] = true;
                    }else{
                        dp[i][j] = dp[i+1][j-1];
                    }
                }

                if(dp[i][j] == true && maxLen < L){
                    maxLen = L;
                    begin = i;
                }
            }
        }

        return s.substring(begin,maxLen+begin);
    }
}
